package com.example.thirdhomework

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity

class FourthActivity : AppCompatActivity() {
    companion object {
        const val REQUEST_IMAGE_CAPTURE = 1 // 请求码，用于识别拍照请求
    }

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_fourth) // 设置布局文件

        val button = findViewById<Button>(R.id.take_photo) // 获取拍照按钮
        button.setOnClickListener {
            dispatchTakePictureIntent() // 设置按钮点击事件，调用拍照方法
        }
    }

    private fun dispatchTakePictureIntent() {
        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) // 创建拍照意图
        if (takePictureIntent.resolveActivity(packageManager) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE) // 启动拍照活动
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            val imageBitmap = data?.extras?.get("data") as Bitmap // 获取拍照结果
            val imageView = findViewById<ImageView>(R.id.imageView) // 获取ImageView
            imageView.setImageBitmap(imageBitmap) // 显示拍照结果
        }
    }
}